﻿using Autofac;
using Autofac.Integration.Mvc;
using AutoMapper;
using Owin;
using System.Web.Mvc;
using Yz.Cache;
using Yz.DataAccess.ModelMapper;
using Yz.Mvc.Startups;

namespace Yz.Web
{
    public static partial class StartupExtension
    {
        /// <summary>
        /// autofac的注入
        /// </summary>
        /// <param name="app"></param>
        public static void RegisterAutofac(this IAppBuilder app)
        {
            //创建autofac管理注册类的容器实例
            var builder = StartupAutofac.RegisterService();

            #region 缓存注入 (手动注入) 
            builder.RegisterType<CacheRedisUitility>()
          .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<ICacheUitility>()
          .InstancePerLifetimeScope();
            #endregion
            builder.Register<IConfigurationProvider>(ctx => new MapperConfiguration(x =>
            {
                x.AddProfile<SourceProfileApi>();
                x.AddProfile<SourceProfileVm>();
            })).PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).InstancePerLifetimeScope();
            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //生成具体的实例 
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired(); ////// 使用这一种注入controller或者使用上边的这一种（Yz.Mvc父类也要注入）
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();
        }
    }
}